<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <XForm ref="form" :fieldList="fieldList" :options="formOption" :formData="form">
          <template #ShopCascade>
            <SelectsShopCascade v-model:platform="form.platform" v-model:site="form.site" v-model:shop="form.shop" />
          </template>
        </XForm>
      </template>
      <template #toolbar_btns>
        <el-dropdown trigger="click" @command="batchOptionsEvent">
          <el-button type="primary">
            批量操作
            <div class="dk-iconfont icon-ArrowDown ml-[4px]"></div>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu v-matomo>
              <template v-for="item in batchOptions">
                <el-dropdown-item :command="item.value" v-if="isPermission(item.permission)" :key="item">{{ item.label }}</el-dropdown-item>
              </template>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <!-- <VButton @click="handleStaus(1)" v-hasPermi="[basicSetupAuthList.order_source.enable]">
          <div class="dk-iconfont icon-CircleCheck text-[#3487FF]"></div>
          启用
        </VButton>
        <VButton @click="handleStaus(0)" v-hasPermi="[basicSetupAuthList.order_source.disable]">
          <div class="dk-iconfont icon-Disabled text-[red]"></div>
          禁用
        </VButton> -->
      </template>
    </VTable>
    <!-- <VLog ref="logRef" :api="getOplog"></VLog> -->
    <Log dialog v-model="logVisible" :autoLoad="false" tag="order_source_channel" :business_id="logId" />

    <!-- 下载订单 -->
    <VdownloadOrder ref="downloadOrder" :options="is_download_orders" @query="query"></VdownloadOrder>
    <!-- 批量设置生成追踪号 -->
    <VtraceNumber ref="traceNumber" :options="is_pre_generate" @query="query"></VtraceNumber>
    <!-- 批量设置标记平台发货 -->
    <VmarkingPlatformDelivery ref="markingPlatformDelivery" :options="is_platform_shipment" @query="query"></VmarkingPlatformDelivery>
    <!-- 批量设置客服人员 -->
    <VcustomerService ref="customerService" @query="query"></VcustomerService>
    <!-- 批量设置IOSS税号 -->
    <VIOSSNumber ref="IOSSNumber" @query="query"></VIOSSNumber>
    <!-- 批量上传店铺发货地址 -->
    <VshippingAddress ref="shippingAddress" class="dialogPublic" @query="query"></VshippingAddress>
    <!-- 批量上传店铺发票地址 -->
    <VInvoiceAddress ref="InvoiceAddress" class="dialogPublic" @query="query"></VInvoiceAddress>
  </VPage>
</template>

<script setup lang="jsx" name="Basic-setupOrder-source">
import VdownloadOrder from "./components/downloadOrder"
import VcustomerService from "./components/customerService"
import VIOSSNumber from "./components/IOSSNumber"
import VmarkingPlatformDelivery from "./components/markingPlatformDelivery"
import VshippingAddress from "./components/shippingAddress"
import VtraceNumber from "./components/traceNumber"
import VInvoiceAddress from "./components/InvoiceAddress"
import { overallOptions } from "@/api/public"
import { queryList, getOplog, batchUpdate } from "./api/index.js"
// import VLog from "@/components/VLog"

import Log from "@/components/Log/index.vue"
const logVisible = ref(false)
const logId = ref("")
const viewLog = (item) => {
  logId.value = item.id
  logVisible.value = true
}

import SelectPlatformSiteShop from "@/components/Selects/SelectPlatformSiteShop/index.vue"
import SelectsShopCascade from "@/components/Selects/SelectsShopCascade/index.vue"
import { ElMessage } from "element-plus"
import { toRefs } from "vue"

import XForm from "@/components/XForm/index.vue"
import { basicSetupAuthList } from "@/Auth/basic-setup.js"
import { isPermission } from "@/hooks/permission.js"

const downloadOrder = ref()
const customerService = ref()
const IOSSNumber = ref()
const markingPlatformDelivery = ref()
const shippingAddress = ref()
const traceNumber = ref()
const InvoiceAddress = ref()

const batchOptions = [
  {
    label: "批量设置下载订单",
    value: "0",
    permission: [basicSetupAuthList.order_source.batchDownload],
  },
  {
    label: "批量设置生成追踪号",
    value: "1",
    permission: [basicSetupAuthList.order_source.batchTrackingNumber],
  },
  {
    label: "批量设置标记平台发货",
    value: "2",
    permission: [basicSetupAuthList.order_source.batchPublish],
  },
  {
    label: "批量设置客服人员",
    value: "3",
    permission: [basicSetupAuthList.order_source.batchService],
  },
  {
    label: "批量设置IOSS税号",
    value: "4",
    permission: [basicSetupAuthList.order_source.batchIoss],
  },
  {
    label: "批量上传店铺发货地址",
    value: "5",
    permission: [basicSetupAuthList.order_source.batchShopAddress],
  },
  {
    label: "批量上传店铺发票地址",
    value: "6",
    permission: [basicSetupAuthList.order_source.batchShopInvoice],
  },
]

// const personnelOptions = [
//   {
//     label: '店铺负责人',value: 'shop_manager_id'
//   },
//   {
//     label: '店铺店员',value: 'shop_clerks_id'
//   },
//   {
//     label: '客服人员',value: 'customer_service_id'
//   },
// ]

const data = reactive({
  statusOption: [],
  is_download_orders: [],
  is_platform_shipment: [],
  is_pre_generate: [],
  order_priority_level: [],
})
const { statusOption, is_download_orders, is_platform_shipment, is_pre_generate, order_priority_level } = toRefs(data)
// const isOpen = [{
//   label: '开启', value: '1'
// }, {
//   label: '关闭', value: '0'
// }]
const tableRef = ref()
// const logRef = ref()
// const loadings = reactive({})

// 1 启用  0 禁用
const handleStaus = (status) => {
  if (!getSelectRow().length) {
    return false
  }
  const arr = getSelectRow()
  batchUpdate({ ids: arr, orderSource: { status: status } }).then((res) => {
    ElMessage.success("操作成功")
    query()
  })
}

//批量操作
const batchOptionsEvent = (val) => {
  if (!getSelectRow().length) {
    return false
  }
  const arr = getSelectRow()
  switch (val) {
    case "0":
      downloadOrder?.value.open(arr)
      break
    case "1":
      traceNumber?.value.open(arr)
      break
    case "2":
      markingPlatformDelivery?.value.open(arr)
      break
    case "3":
      customerService?.value.open(arr)
      break
    case "4":
      IOSSNumber?.value.open(arr)
      break
    case "5":
      shippingAddress?.value.open("batch", arr)
      break
    case "6":
      InvoiceAddress?.value.open(arr)
      break
  }
}
const formOption = ref({
  inline: true,
})
const publicStyle = { style: { width: "180px" } }
const indicatorTypeOpt = ref([]) //指标
const fieldList = ref([
  {
    slot: "ShopCascade",
  },
  {
    field: "personnelRange",
    type: "cascader",
    itemProps: { placeholder: "人员" },
    style: { width: "300px" },
    select: [
      { label: "店铺负责人", value: "shop_manager_id" },
      { label: "店铺店员", value: "shop_clerks_id" },
      { label: "客服人员", value: "customer_service_id" },
    ],
    selectStyle: { width: "120px" },
  },

  {
    field: "order_priority_level",
    type: "select",
    options: {
      placeholder: "订单优先级",
      data: order_priority_level,
    },
    ...publicStyle,
  },
  {
    field: "is_download_orders",
    type: "select",
    options: {
      placeholder: "是否下载订单",
      data: is_download_orders,
    },
    ...publicStyle,
  },
  {
    field: "is_pre_generate",
    type: "select",
    options: {
      placeholder: "是否预生成追踪号",
      data: is_pre_generate,
    },
    ...publicStyle,
  },
  {
    field: "is_platform_shipment",
    type: "select",
    options: {
      placeholder: "是否标记平台发货",
      data: is_platform_shipment,
    },
    ...publicStyle,
  },
])

// 查询
const query = () => {
  tableRef?.value.query()
}
//打开详情
// const showDetail = () => {
//   // useRouter/oms/basic-setup/order-source
// }

//获取已选中的行
const getSelectRow = () => {
  const getCheckboxRecords = tableRef?.value.$table.getCheckboxRecords()
  if (!getCheckboxRecords.length) {
    ElMessage({
      showClose: true,
      message: "请至少选择一条数据！",
      type: "warning",
    })
    return false
  }
  const arr = []
  getCheckboxRecords.map((e) => {
    arr.push(e.id)
  })
  return arr
}
// 列表配置
const tableOptins = reactive({
  formConfig: {
    data: {
      platform: "",
      site: [],
      shop: [],
      status: "",
      // shop_manager_id: [],
      shop_clerks_id: [],
      customer_service_id: [],
      order_priority_level: "",
      is_download_orders: "",
      is_pre_generate: "",
      is_platform_shipment: "",
      personnelRange: { type: "shop_manager_id", value: "" },
    },
  },
  showOverflow: true,
  columns: [
    { type: "checkbox", fixed: "left", width: 60 },
    { field: "id", title: "ID", width: 60 },
    {
      field: "platform",
      title: "平台/站点",
      width: 120,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {row.platform}/{row.site}
            </div>
          )
        },
      },
    },
    {
      field: "shop_code",
      title: "渠道店铺名称/真实店铺名称",
      minWidth: 220,
      slots: {
        default: ({ row }) => {
          return <VText value={`${row.shop}/${row.real_shop_name}`} />
        },
      },
    },
    { field: "operating_costs", title: "预设运营费用", minWidth: 120 },
    { field: "shop_manager", title: "店铺负责人员", minWidth: 120 },
    {
      field: "shop_clerks",
      title: "店铺店员",
      minWidth: 200,
      slots: {
        default: ({ row }) => {
          const names = row.shop_clerks
          const shop_clerks = names?.join(",")
          return <VText value={shop_clerks} />
        },
      },
    },
    { field: "customer_service", title: "客服人员", minWidth: 120 },
    {
      title: "状态",
      field: "status_text",
      width: 100,
      slots: {
        default: ({ row }) => <VStatus value={row.status_text === "启用"} />,
      },
    },
    { field: "create_time", title: "创建时间", width: 170 },
    { field: "update_time", title: "更新时间", width: 170 },
    {
      title: "操作",
      width: 110,
      fixed: "right",
      slots: {
        default: ({ row }) => {
          return [
            <div>
              <el-button link type="primary" onClick={() => gotoEdit(row.id)} v-hasPermi={[[basicSetupAuthList.order_source.edit]]}>
                编辑
              </el-button>
              <el-button link type="primary" onClick={() => viewLog(row)} v-hasPermi={[[basicSetupAuthList.order_source.log]]}>
                日志
              </el-button>
            </div>,
          ]
        },
      },
    },
  ],
  proxyConfig: {
    props: {
      result: "data",
      total: "total",
    },
    ajax: {
      query: ({ page, form }) => {
        let formData = { ...form, ...page }
        // formData.platform = formData.platform ? [formData.platform] : []
        tableRef?.value?.$table.reloadData([])
        return queryList(formData)
      },
    },
  },
})

const router = useRouter()
const gotoEdit = (id) => {
  router.push({
    path: "/basic-setup/order-source/add",
    query: {
      id,
    },
  })
}
//获取下拉数据
onMounted(() => {
  overallOptions({ params: ["base.orderSourceChannel"] }).then((res) => {
    statusOption.value = res.data.baseOrderSourceChannel.status
    is_download_orders.value = res.data.baseOrderSourceChannel.is_download_orders.map((v) => ({ ...v, value: String(v.value) }))
    is_platform_shipment.value = res.data.baseOrderSourceChannel.is_platform_shipment.map((v) => ({ ...v, value: String(v.value) }))
    is_pre_generate.value = res.data.baseOrderSourceChannel.is_pre_generate.map((v) => ({ ...v, value: String(v.value) }))
    order_priority_level.value = res.data.baseOrderSourceChannel.order_priority_level
  })
})
</script>
<style lang="scss" scoped></style>
